"use strict";
const path = require("path");

function resolve(dir) {
  return path.join(__dirname, dir);
}
const defaultSettings = require("./src/settings.js");
// 导入compression-webpack-plugin
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const FileManagerPlugin = require('filemanager-webpack-plugin');
// 定义压缩文件类型
const productionGzipExtensions = ["js", "css", "ttf", "otf", "woff", "woff2"];

const name = defaultSettings.title || "video"; // 标题
const port = process.env.port || 80; // 端口
module.exports = {
  runtimeCompiler: true,
  publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
  outputDir: "dist",
  assetsDir: "static",
  lintOnSave: process.env.NODE_ENV === "development",
  productionSourceMap: false,
  css: {
    extract: process.env.NODE_ENV === "production" ? {
      ignoreOrder: true,
    } : false,
    loaderOptions: {
      sass: {
        sassOptions: {
          outputStyle: 'expanded'
        }
      }
    }
  },
  devServer: {
    host: "0.0.0.0",
    port: port,
    open: true,
    //启动gzip压缩
    compress: true,
    proxy: {
      ["/files"]: {
        target: `http://172.17.1.206:15010/files`,
        changeOrigin: true,
        pathRewrite: {
          ["^" + "/files"]: "",
        },
      },
      [process.env.VUE_APP_BASE_API]: {
        target: `http://127.0.0.1:14000/api/v1`,
        changeOrigin: true,
        pathRewrite: {
          ["^" + process.env.VUE_APP_BASE_API]: "",
        },
      },
    },
    disableHostCheck: true,
  },
  configureWebpack: {
    name: name,
    // eval-source-map 编译慢 热更新较快
    devtool: process.env.NODE_ENV === "development" ? "eval-source-map" : undefined, // 在浏览器中展示源代码
    resolve: {
      alias: {
        "@": resolve("src"),
      },
    },
    // output: { // 输出重构  打包编译后的 文件名称  【模块名称.js】
    //   filename: 'js/[name].js',
    //   chunkFilename: 'js/[name].js'
    // },
    performance: {
      hints: "warning",
      // 入口起点的最大体积
      maxEntrypointSize: 100000000,
      // 生成文件的最大体积
      maxAssetSize: 100000000,
      // 只给出 js 文件的性能提示
      assetFilter: function (assetFilename) {
        return assetFilename.endsWith(".js");
      },
    },
    plugins: [],
  },
  chainWebpack(config) {
    config.plugins.delete("preload");
    config.plugins.delete("prefetch");

    config.plugin('html').tap(args => {
      const version = process.env.VERSION || 'v1'
      args[0].favicon = path.resolve(__dirname, `public/${version}/favicon.ico`)
      return args
    })

    if (process.env.NODE_ENV == "report") {
      config
        .plugin("webpack-bundle-analyzer")
        .use(require("webpack-bundle-analyzer").BundleAnalyzerPlugin);
    }
    // set svg-sprite-loader
    config.module.rule("svg").exclude.add(resolve("src/assets/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();
    config.when(process.env.NODE_ENV !== "development", (config) => {
      // 这个配置会把error信息也不打印 先注释掉
      // config.optimization.minimizer('terser').tap((args) => {
      //   args[0].parallel = 4;
      //   args[0].terserOptions.compress.warnings = true;
      //   args[0].terserOptions.compress.drop_debugger = true;
      //   args[0].terserOptions.compress.drop_console = true;
      //   args[0].terserOptions.compress.pure_funcs = ['console.log', 'console.info'];
      //   return args
      // });

      config.plugin("fileManager").use(new FileManagerPlugin({
        events: {
          onEnd: {
            delete: ['./dist.zip'],
            archive: [{
              source: path.join(__dirname, './dist'),
              destination: path.join(__dirname, './dist.zip')
            }]
          }
        }
      }));

      config
        .plugin("ScriptExtHtmlWebpackPlugin")
        .after("html")
        .use("script-ext-html-webpack-plugin", [{
          inline: /runtime\..*\.js$/,
        },])
        .end();

      config
        .plugin("compressionPlugin")
        .use(
          new CompressionWebpackPlugin({
            filename: "[path].gz[query]",
            algorithm: "gzip",
            test: new RegExp(
              "\\.(" + productionGzipExtensions.join("|") + ")$"
            ),
            threshold: 10240,
            minRatio: 0.8,
          })
        )
        .end();

      // 打包时 将组件分割打包
      let cacheGroups = {
        libs: {
          name: "chunk-libs",
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: "initial",
        },
        commons: {
          enforce: true,
          name: "chunk-commons",
          test: resolve("src/components"),
          minChunks: 1,
          priority: 20,
          reuseExistingChunk: true,
          chunks: "async",
        },
      };
      config.optimization.splitChunks({
        chunks: "all",
        cacheGroups: cacheGroups,
      });
      config.optimization.runtimeChunk("single"), {
        from: path.resolve(__dirname, "./public/robots.txt"), //防爬虫文件
        to: "./", //到根目录下
      },
        config.optimization.runtimeChunk("single"), {
        from: path.resolve(__dirname, "./public/config.js"), //防爬虫文件
        to: "./", //到根目录下
      };
    });
  },
};
